package com.example.qxfw.ldyj.controller;

import com.example.qxfw.common.SysResult;
import com.example.qxfw.common.entity.xt.SysConfig;
import com.example.qxfw.common.entity.zy.ThunderFcst;
import com.example.qxfw.common.util.DateUtil;
import com.example.qxfw.common.util.FileUtil;
import com.example.qxfw.ldyj.service.QsybSevice;
import com.example.qxfw.ybzz.service.SysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.List;

@Api(tags = "雷电气象--潜势预报")
@RestController
@CrossOrigin
@RequestMapping("/qsyb")
public class QsybController {

    @Autowired
    private QsybSevice qsybSevice;

    @Autowired
    private SysConfigService sysConfigService;

    @ApiOperation("根据起报时间预报时次预报时效获取雷电预报表信息")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "time", value = "时间 yyyy-MM-dd （2024-04-07）", dataType = "String", required = true),
            @ApiImplicitParam(name = "forecasttime", value = "时次 08/20", dataType = "String", required = true),
            @ApiImplicitParam(name = "forecastntimes", value = "时效 6/12/24/48/.../168", dataType = "String", required = true)
    })
    @GetMapping("selectByReporttimeAndForecasttimeAndForecastntimesOfThunderFcst")
    public SysResult selectByReporttimeAndForecasttimeAndForecastntimesOfThunderFcst(
            String time, String forecasttime, Short forecastntimes
    ) {
        String formattedTime = forecasttime + ":00:00";
        StringBuilder builder = new StringBuilder();
        builder.append(time);
        builder.append(" ");
        builder.append(formattedTime);
        Timestamp reporttime = DateUtil.localDateTimeToTimestamp(DateUtil.stringToLocalDateTime(builder.toString()));
        List<ThunderFcst> list = qsybSevice.
                selectByReporttimeAndForecasttimeAndForecastntimesOfThunderFcst(reporttime, forecasttime, forecastntimes
                );
        return SysResult.success(list);
    }


    @ApiOperation("获取期号")
    @GetMapping("/getDocNumber")
    public SysResult getWeekDocNumber() {
        List<SysConfig> configList = sysConfigService.getList1();
        String dm_LdDocNumber = "0";
        for (SysConfig sys : configList) {
            if (sys.getParamname().equals("dm_qsybqh")) {
                dm_LdDocNumber = sys.getParamvalue();
                break;
            }
        }
        return SysResult.success(dm_LdDocNumber);
    }


    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "time", value = "时间 yyyy-MM-dd （2024-04-07）", dataType = "String", required = true),
            @ApiImplicitParam(name = "forecasttime", value = "时次 08/20", dataType = "String", required = true),
            @ApiImplicitParam(name = "forecastntimes", value = "时效 6/12/24/48/.../168", dataType = "String", required = true),
            @ApiImplicitParam(name = "number", value = "期号", dataType = "String", required = true)
    })
    @ApiOperation("雷电潜势预报文档制作")
    @GetMapping("/createDoc")
    public void createDoc(String time, String forecasttime, Short forecastntimes, String number, String maker, HttpServletResponse response) throws IOException, ParseException {
        ApplicationHome applicationHome = new ApplicationHome(FileUtil.class);
        String filename = time + "_" + forecasttime + "_LXQS" + number+".doc";
        String filePath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
                "\\src\\main\\resources\\temp\\" + filename + ".pdf";

        String formattedTime = forecasttime + ":00:00";
        StringBuilder builder = new StringBuilder();
        builder.append(time);
        builder.append(" ");
        builder.append(formattedTime);
        Timestamp reporttime = DateUtil.localDateTimeToTimestamp(DateUtil.stringToLocalDateTime(builder.toString()));
        List<ThunderFcst> list = qsybSevice.
                selectByReporttimeAndForecasttimeAndForecastntimesOfThunderFcst(reporttime, forecasttime, forecastntimes
                );
        qsybSevice.createDoc(list, filename, time, forecasttime, forecastntimes, number,  maker);
        InputStream inputStream = Files.newInputStream(Paths.get(filePath));
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("" + filename + ".pdf", "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
    }
}
